﻿using SSC.Models;
using SSC.Services;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using SSC.BaseClass;

namespace SSC.ViewModels
{
    public class PartViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<PartModel> Parts { get; set; } = new ObservableCollection<PartModel>();

        private PartModel _selectedPart;
        public PartModel SelectedPart
        {
            get => _selectedPart;
            set
            {
                _selectedPart = value;
                OnPropertyChanged(nameof(SelectedPart));
            }
        }
        #region 通知属性
        private string _selectedSlot; //当前选中的槽号
        public string SelectedSlot
        {
            get => _selectedSlot;
            set
            {
                if (_selectedSlot != value)
                {
                    _selectedSlot = value;
                    OnPropertyChanged(nameof(SelectedSlot));
                }
            }
        }
        private string _partName;
        public string PartName
        {
            get => _partName;
            set
            {
                _partName = value;
                OnPropertyChanged(nameof(PartName));
            }
        }

        private string _batchNumber;
        public string BatchNumber
        {
            get => _batchNumber;
            set
            {
                _batchNumber = value;
                OnPropertyChanged(nameof(BatchNumber));
            }
        }

        private string _areaA;
        public string AreaA
        {
            get => _areaA;
            set
            {
                _areaA = value;
                OnPropertyChanged(nameof(AreaA));
            }
        }

        private string _areaB;
        public string AreaB
        {
            get => _areaB;
            set
            {
                _areaB = value;
                OnPropertyChanged(nameof(AreaB));
            }
        }

        private string _goldTime;
        public string GoldTime
        {
            get => _goldTime;
            set
            {
                _goldTime = value;
                OnPropertyChanged(nameof(GoldTime));
            }
        }

        private string _nieTime;
        public string NieTime
        {
            get => _nieTime;
            set
            {
                _nieTime = value;
                OnPropertyChanged(nameof(NieTime));
            }
        }

        private string _preGoldCurrentA;
        public string PreGoldCurrentA
        {
            get => _preGoldCurrentA;
            set
            {
                _preGoldCurrentA = value;
                OnPropertyChanged(nameof(PreGoldCurrentA));
            }
        }

        private string _preGoldCurrentB;
        public string PreGoldCurrentB
        {
            get => _preGoldCurrentB;
            set
            {
                _preGoldCurrentB = value;
                OnPropertyChanged(nameof(PreGoldCurrentB));
            }
        }

        private string _goldCurrentA;
        public string GoldCurrentA
        {
            get => _goldCurrentA;
            set
            {
                _goldCurrentA = value;
                OnPropertyChanged(nameof(GoldCurrentA));
            }
        }

        private string _goldCurrentB;
        public string GoldCurrentB
        {
            get => _goldCurrentB;
            set
            {
                _goldCurrentB = value;
                OnPropertyChanged(nameof(GoldCurrentB));
            }
        }

        private string _nieCurrentA;
        public string NieCurrentA
        {
            get => _nieCurrentA;
            set
            {
                _nieCurrentA = value;
                OnPropertyChanged(nameof(NieCurrentA));
            }
        }

        private string _nieCurrentB;
        public string NieCurrentB
        {
            get => _nieCurrentB;
            set
            {
                _nieCurrentB = value;
                OnPropertyChanged(nameof(NieCurrentB));
            }
        }
        #endregion
        public string SearchBatchNumber { get; set; }

        public ICommand SearchCommand => new RelayCommand(_ => Search());
        public ICommand AddCommand => new RelayCommand(_ => Add());
        public ICommand UpdateCommand => new RelayCommand(_ => Update());
        public ICommand DeleteCommand => new RelayCommand(_ => Delete());
        public ICommand FeedCommand => new RelayCommand(async _ => await FeedAsync());

        public PartViewModel()
        {
            _partName = "";
            _batchNumber = "";
            _areaA = "";
            _areaB = "";
            _goldTime = "";
            _nieTime = "";
            _preGoldCurrentA = "";
            _preGoldCurrentB = "";
            _goldCurrentA = "";
            _goldCurrentB = "";
            _nieCurrentA = "";
            _nieCurrentB = "";

            LoadData();
        }

        private void LoadData()
        {
            Parts.Clear();
            var all = PartService.GetPartModels();
            foreach (var item in all)
            {
                Parts.Add(item);
            }
        }

        private void Search()
        {
            var filtered = PartService.GetPartModels()
                .Where(p => p.BatchNumber.Contains(SearchBatchNumber ?? ""))
                .ToList();

            Parts.Clear();
            foreach (var item in filtered)
            {
                Parts.Add(item);
            }
        }

        private void Add()
        {
            // 创建一个新的 PartModel 实例
            var newPart = new PartModel
            {
                PartName = SelectedPart?.PartName,
                BatchNumber = SelectedPart?.BatchNumber,
                AreaA = SelectedPart?.AreaA,
                AreaB = SelectedPart?.AreaB,
                GoldA = SelectedPart?.GoldA,
                GoldB = SelectedPart?.GoldB,
                PreGoldA = SelectedPart?.PreGoldA,
                PreGoldB = SelectedPart?.PreGoldB,
                NieA = SelectedPart?.NieA,
                NieB = SelectedPart?.NieB,
                GoldTime = SelectedPart?.GoldTime,
                NieTime = SelectedPart?.NieTime
            };

            // 检查料号和工单号是否为空
            if (string.IsNullOrWhiteSpace(newPart.PartName))
            {
                MessageBox.Show("料号不能为空");
                return;
            }

            if (string.IsNullOrWhiteSpace(newPart.BatchNumber))
            {
                MessageBox.Show("工单号不能为空");
                return;
            }

            // 检查是否存在相同的 PartName
            if (PartService.IsPartNameExists(newPart.PartName))
            {
                MessageBox.Show("料号已存在，请输入不同的料号");
                return;
            }

            // 设置添加时间
            newPart.DateTime = DateTime.Now.ToString();

            // 调用服务方法新增料号
            if (PartService.AddPartModel(newPart))
            {
                MessageBox.Show("新增成功");
                LoadData();
            }
            else
            {
                MessageBox.Show("新增失败");
            }
        }

        private void Update()
        {
            if (SelectedPart == null)
            {
                MessageBox.Show("请先选择要修改的项");
                return;
            }

            SelectedPart.DateTime = DateTime.Now.ToString();

            if (PartService.UpdatePartModel(SelectedPart))
            {
                MessageBox.Show("修改成功");
                LoadData();
            }
            else
            {
                MessageBox.Show("修改失败");
            }
        }

        private void Delete()
        {
            if (SelectedPart == null)
            {
                MessageBox.Show("请选择要删除的项");
                return;
            }

            if (PartService.DeletePartModel((int)SelectedPart.Id))
            {
                MessageBox.Show("删除成功");
                LoadData();
            }
            else
            {
                MessageBox.Show("删除失败");
            }
        }
        //上料方法
        private async Task FeedAsync()
        {
            if (SelectedPart == null)
            {
                MessageBox.Show("请先选择一个料号（配方）！");
                return;
            }
            if (Variable.PlcConnection==null)
            {
                MessageBox.Show("PLC未连接");
                return;
            }
            string partName = SelectedPart.PartName;

            // 生成唯一 Pcode（类型为 short）
            short pcode;
            int tryCount = 0;
            do
            {
                int rawCode = DateTime.Now.Minute * 100 + DateTime.Now.Second;
                pcode = (short)(rawCode % 32767);
                tryCount++;
                if (tryCount > 5)
                {
                    MessageBox.Show("生成唯一Pcode失败，请稍后再试！");
                    return;
                }
            } while (ProductManager.Instance.ContainsPcode(pcode.ToString()));

            var product = new ProductModel(pcode.ToString(), partName);
            if (!ProductManager.Instance.AddProduct(product))
            {
                MessageBox.Show("产品添加失败，Pcode重复！");
                return;
            }

            int slot = 0; // 你可以提供绑定属性来选择槽位
            string address = PlcAddress.GetPcodeAddress(slot);
            var result = await Variable.PlcConnection.WriteSingle(address, pcode);
            if (!result)
            {
                MessageBox.Show("写入PLC失败");
                return;
            }

            MessageBox.Show($"上料成功：{partName}（Pcode: {pcode}）已写入槽位 {slot}");
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string name) =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}
